package com.bruce.service;

import com.spring.BruceApplicationContext;
import com.spring.annotation.Component;
import com.spring.inter.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Bruce
 */
@Component("bruceBeanPostProcessor")
public class BruceBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessorBeforeInitialization(Object bean, String beanName) {
        return bean;
    }

    @Override
    public Object postProcessorAfterInitialization(Object bean, String beanName) {

        System.out.println("after init...");

        if ("userService".equals(beanName)) {

            // TODO 这里动态代理有个异常之后再看
            // Exception in thread "main" java.lang.ClassCastException: class jdk.proxy2.$Proxy4 cannot be cast to class com.bruce.service.UserService (jdk.proxy2.$Proxy4 is in module jdk.proxy2 of loader 'app'; com.bruce.service.UserService is in unnamed module of loader 'app') at com.bruce.Test.main(Test.java:13)
//            Object proxyInstance = Proxy.newProxyInstance(BruceApplicationContext.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
//                @Override
//                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                    System.out.println("proxy process...");
//                    return method.invoke(bean, args);
//                }
//            });
//
//            return proxyInstance;
        }

        return bean;
    }
}
